package com.cloudstudy.tool;

import java.security.SecureRandom;
import java.util.*;

public class SeqTool {
    private final static int length = 32;

    private static SecureRandom random = new SecureRandom();

    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.  32位长度。一般用它
     */
    public static String uuid() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        if (uuid.length() < length){
            uuid = uuid + generateNumberString(length - uuid.length());
        }
        return uuid;
    }

    /**
     * 使用SecureRandom随机生成Long.
     */
    public static long genLong() {
        return Math.abs(random.nextLong());
    }

    public static String generate(){

        StringBuilder builder = new StringBuilder();
        String now = DtTool.getDateTime(DtTool.DATE_TIME_MASK4, new Date());
        String code = String.valueOf(Math.abs(new SeqHash().hashCode()));
        String rand = generateNumberString(10);

        builder.append(now)
                .append(code)
                .append(rand);

        int len = builder.toString().length();

        if (len < length) {
            String rand2 = generateNumberString(length-len);
            builder.append(rand2);
        }
        if (len > length){
            return builder.toString().substring(0,length);
        }
//        System.out.println(builder.toString());

        return builder.toString();
    }

    /**
     * 获取定长的随机数,只包含数字
     * @param length 随机数长度
     * @return
     */
    public static String generateNumberString(int length){
        String NUMBER_CHAR = "0123456789";
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(NUMBER_CHAR.charAt(random.nextInt(NUMBER_CHAR.length())));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String seq = uuid();
        System.out.println(seq);
        System.out.println(seq.length());

        seq = String.valueOf(genLong());
        System.out.println(seq);
        System.out.println(seq.length());

        test(10);
    }

    /**
     * 防止重复测试
     * 跑了600* 1000000 次，没有重复发生
     * @author Tony
     * @since 2021/2/7
     */
    private static int test(int j) {
        Set<String> set2 = new HashSet<String>();
        for(int i = 0; i<1000000; i++){
            set2.add(uuid());
        }
//        System.out.println((j+1)+": "+set2.size());
        return set2.size();
    }
}

class SeqHash{
    private Date salt = new Date();
    public SeqHash(){ }
}

